package thread_test;

// 测试 notifyAll() 方法
public class NotifyAllDemo {
    public static void main(String[] args) {
        Object locker = new Object();
        Thread t1 = new Thread(()->{
            synchronized (locker) {
                System.out.println("执行线程 t1 的 wait 方法前");
                try {
                    locker.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("t1 线程被唤醒");
            }
        });
        Thread t2 = new Thread(()->{
            synchronized (locker) {
                System.out.println("执行线程 t2 的 wait 方法前");
                try {
                    locker.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("t2 线程被唤醒");
            }
        });
        Thread t3 = new Thread(()->{
            synchronized (locker) {
                System.out.println("执行线程 t3 的 wait 方法前");
                try {
                    locker.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("t3 线程被唤醒");
            }
        });
        Thread t4 = new Thread(()->{
            // 休眠 t4 线程 3s 让前三个线程先执行完 wait 方法
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            synchronized (locker) {
                System.out.println("唤醒全部线程.....");
                locker.notifyAll();
            }
        });
        // 启动所有线程,观察结果
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}
